import { defineStore } from 'pinia';

import { ITabMenu } from './type';
import router from '@/router';

export const useTabsStore = defineStore('tabsStore', () => {
    const tabsMenuList = ref<ITabMenu[]>([]);
    const addTabs = (tabItem: ITabMenu) => {
        if (tabsMenuList.value.every((item) => item.path !== tabItem.path)) {
            if (tabItem.name === 'Home') {
                tabsMenuList.value.unshift(tabItem);
            } else {
                tabsMenuList.value.push(tabItem);
            }
        }
    };
    const removeTabs = (tabPath: string, isCurrent: boolean = true) => {
        const _tabsMenuList = tabsMenuList.value;
        if (isCurrent) {
            _tabsMenuList.forEach((item, index) => {
                if (item.path !== tabPath) return;
                const nextTab =
                    _tabsMenuList[index + 1] || _tabsMenuList[index - 1];
                if (!nextTab) return;
                router.push(nextTab.path);
            });
        }
        tabsMenuList.value = _tabsMenuList.filter(
            (item) => item.path !== tabPath,
        );
    };
    const closeMultipleTab = (tabPath: string) => {
        tabsMenuList.value = tabsMenuList.value.filter((item) => {
            return item.path === tabPath || !item.close;
        });
    };
    const setTabs = (_tabsMenuList: ITabMenu[]) => {
        tabsMenuList.value = _tabsMenuList;
    };
    const setTabsTitle = (title: string) => {
        const nowFullPath = location.hash.substring(1);
        tabsMenuList.value.forEach((item) => {
            if (item.path == nowFullPath) item.title = title;
        });
    };
    return {
        tabsMenuList,
        addTabs,
        removeTabs,
        closeMultipleTab,
        setTabs,
        setTabsTitle,
    };
});
